#!/bin/bash
echo 'begin...'
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
DEPLOY_DIR=`pwd`
LOGS_DIR=$DEPLOY_DIR/logs
if [ ! -d $LOGS_DIR ]; then
    mkdir $LOGS_DIR
fi
DATA_DIR=$DEPLOY_DIR/data
if [ ! -d $DATA_DIR ]; then
    mkdir $DATA_DIR
fi
TOMCAT_CONF_DIR=$DEPLOY_DIR/myconf/tomcat
if [ -d $TOMCAT_CONF_DIR ]; then
    echo '加载TOMCAT 自定义配置项'
    \cp -rf $TOMCAT_CONF_DIR/* $DEPLOY_DIR/conf
fi
APP_CONF_DIR=$DEPLOY_DIR/myconf/app
if [ -d $APP_CONF_DIR ] && [ -d $DEPLOY_DIR/webapps/ROOT/WEB-INF/classes ]; then
   echo '加载APP自定义配置项'
   \cp -rf $APP_CONF_DIR/* $DEPLOY_DIR/webapps/ROOT/WEB-INF/classes
fi

DISCONF_FILE=$DEPLOY_DIR/webapps/ROOT/WEB-INF/classes/disconf.properties
if [ ! -z "$DISCONF_ENV" ] && [ -a $DISCONF_FILE ]; then
    echo "配置环境设置 $DISCONF_ENV"
    sed -i "s#^env=.*#env=$DISCONF_ENV#g" $DISCONF_FILE;
fi
if [ ! -z "$DUBBO_GROUP_PMSUITE" ]; then
    echo 'dubbo group环境配置'
    sed -i "s#^dubbo.group.pmsuite=.*#dubbo.group.pmsuite=$DUBBO_GROUP_PMSUITE#g" $DEPLOY_DIR/webapps/ROOT/WEB-INF/classes/application.properties;
fi
if [ ! -z "$DUBBO_GROUP_PUBSERVICE" ]; then
    echo 'dubbo pubservice group环境配置'
    sed -i "s#^dubbo.group.pubservice=.*#dubbo.group.pubservice=$DUBBO_GROUP_PUBSERVICE#g" $DEPLOY_DIR/webapps/ROOT/WEB-INF/classes/application.properties;
fi

DOCKER_JAVA_OPTS=""
if [ ! -z "$DOCKER_HOST" ]; then
  echo "配置host:注册的主机ip=$DOCKER_HOST"
  DOCKER_JAVA_OPTS="$DOCKER_JAVA_OPTS -DDUBBO_IP_TO_REGISTRY=$DOCKER_HOST"
fi
if [ ! -z "$DOCKER_PORT" ]; then
    echo "注册的端口号:$DOCKER_PORT"
    DOCKER_JAVA_OPTS="$DOCKER_JAVA_OPTS -DDUBBO_PORT_TO_REGISTRY=$DOCKER_PORT"
    echo "docker端口和注册端口保证一致"
    sed -i "s#^dubbo.port=.*#dubbo.port=$DOCKER_PORT#g" $DEPLOY_DIR/webapps/ROOT/WEB-INF/classes/application.properties;
fi
echo "JVM参数：$DOCKER_JAVA_OPTS"
export DOCKER_JAVA_OPTS
if [ ! -z "$ZOOKEEPER_ADDRESS" ]; then
    echo '发现服务地址不能为空'
    sed -i "s#^zookeeper.address=.*#zookeeper.address=$ZOOKEEPER_ADDRESS#g" $DEPLOY_DIR/webapps/ROOT/WEB-INF/classes/application.properties;
fi
echo -e "Starting  ...\c"
catalina.sh run
echo "exit!"
exit 0;